package edu.whu.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.whu.demo.dao.MessageDao;
import edu.whu.demo.domain.Activity;
import edu.whu.demo.dao.ActivityDao;
import edu.whu.demo.domain.Message;
import edu.whu.demo.exception.ActivityAdminException;
import edu.whu.demo.exception.MessageException;
import edu.whu.demo.service.IActivityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2022-11-24
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityDao, Activity> implements IActivityService {
    //!!!还没做exception
    @Autowired
    ActivityDao activityDao;

    @Autowired
    MessageDao messageDao;

    @Autowired
    MessageServiceImpl messageService;


    //实现整个活动的添加，包括abstract和detail
    @Override
    public Activity addActivity(Activity activity){
        activityDao.insert(activity);
        /*        Message message = new Message();
        message.setType("check");
        message.setToUid(activity.getHostUid());
        message.setFromUid((long) -1);
        message.setActivityId(activity.getId());
        message.setTime(LocalDateTime.now());
        message.setIsRead(0);
        message.setContent("活动审核通过!");
        messageService.addMessage(message);*/
        //异常处理
        return activity;
    }

    //实现整个活动的更新
    @Override
    public void updateActivity(Long id, Activity activity) throws ActivityAdminException {
        if(activityDao.selectById(id) != null){
            activityDao.updateById(activity);
        }
        else{
            throw new ActivityAdminException("修改活动失败，未找到活动");
        }
    }

    //实现整个活动的删除，包括abstract和detail
    @Override
    public void deleteActivity(Long id) throws ActivityAdminException {
        if(activityDao.selectById(id) != null) {
            activityDao.deleteById(id);
            QueryWrapper<Message> wrapper = new QueryWrapper<>();
            wrapper.eq("activity_id",id);
            messageDao.delete(wrapper);
        }
        else{
            throw new ActivityAdminException("删除活动失败，未找到活动");
        }
        //异常处理
    }

    @Override
    public IPage<Activity> findActivity(Map<String, Object> condition,
                                        Integer pageNum,
                                        Integer pageSize){
        //关键字、分类标签、排序标签、
        Page<Activity> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Activity> wrapper = new QueryWrapper<>();
        boolean orderBy = condition.containsKey("orderBy")&&condition.containsKey(condition.get("orderBy"));
        if(orderBy){
            wrapper.orderBy(true, (Boolean) condition.get(condition.get("orderBy")), (String) condition.get("orderBy"));
        }

        if(condition.containsKey("state")){
            wrapper.and((wrap)->{
                //解析state码 editing checking released withdraw end
                int mask = 1;
                String[] state={"editing","checking","released","withdraw","end"};
                for(int i =4;i>=0;i--){
                    if((mask & (Integer) condition.get("state")) != 0){
                        wrap.or().eq("state",state[i]);
                    }
                    mask = mask<<1;
                }
            });
        }


        if(condition.containsKey("byUsername")){
            //利用用户名查找
            wrapper.like(condition.containsKey("keyword"), "u.name", condition.get("keyword")).
                    eq(condition.containsKey("type"), "type", condition.get("type"));
        }
        else {
            if(condition.containsKey("type")){
                if(condition.containsKey("keyword")) {
                    wrapper.and((wrap) -> {
                        wrap.like("a.name", condition.get("keyword")).or()
                                .like("a.info", condition.get("keyword"));
                    });
                }
                wrapper.eq(condition.containsKey("type"), "type", condition.get("type"));
            }
            else{
                wrapper.like(condition.containsKey("keyword"), "a.name", condition.get("keyword")).or().
                        like(condition.containsKey("keyword"), "a.info", condition.get("keyword"));
            }
        }

        wrapper.eq(condition.containsKey("hostUid"), "host_uid", condition.get("hostUid"));

        return activityDao.findActivity(page,wrapper);
    }

    public Activity isPresent(Activity abstractActivity){
        QueryWrapper<Activity> wrapper = new QueryWrapper<>();
        wrapper.eq("name",abstractActivity.getName());
        List<Activity> activities = activityDao.selectList(wrapper);
        if (activities.size()==1){
            return activities.get(0);
        }else {
            for (Activity activity : activities) {
                if (activity.getInfo().equals(abstractActivity.getInfo())){
                    return activity;
                }
            }
        }
        return null;
    }

    public String getChangeContent(Activity Old,Activity New){
        StringBuilder result = new StringBuilder();
        if(!Old.getName().equals(New.getName())){
            result.append("活动名称已改变！"+"现在的名称是"+New.getName()+"\n");
        }
        if(!Old.getBeginTime().equals(New.getBeginTime())){
            result.append("活动开始时间已改变！"+"现在的开始时间是"+New.getBeginTime()+"\n");
        }
        if(!Old.getEndTime().equals(New.getEndTime())){
            result.append("活动结束时间已改变！"+"现在的结束时间是"+New.getEndTime()+"\n");
        }
        if(!Old.getInfo().equals(New.getInfo())){
            result.append("活动简介已改变！"+"现在的简介是"+New.getInfo()+"\n");
        }
        if(!Old.getContent().equals(New.getContent())){
            result.append("活动内容已改变！"+"现在的内容是"+New.getContent()+"\n");
        }
        if(!Old.getPlace().equals(New.getPlace())){
            result.append("活动地点已改变！"+"现在的地点是"+New.getPlace()+"\n");
        }
        if(!Old.getType().equals(New.getType())){
            result.append("活动类型已改变！"+"现在的类型是"+New.getType()+"\n");
        }
        if(!Old.getStageNames().equals(New.getStageNames())){
            result.append("活动总阶段已改变！"+"现在的活动总阶段是"+New.getStageNames()+"\n");
        }
        return result.toString();
    }

    @Override
    public void verifyActivity(Long id, Boolean verify) throws ActivityAdminException, MessageException {
        //审核活动
        Activity activity = activityDao.selectById(id);

        Message message = new Message();
        message.setType("check");
        message.setToUid(activity.getHostUid());
        message.setFromUid((long) -1);    // from管理员的uid就没必要知道了吧
        message.setActivityId(activity.getId());
        message.setTime(LocalDateTime.now());
        message.setIsRead(0);

        // 根据verify来设置state
        if(Objects.equals(activity.getState(), "checking")
                ||Objects.equals(activity.getState(),"withdraw")){
            if(verify)
            {
                activity.setState("released");
                activityDao.updateById(activity);
                message.setContent("活动审核通过!");
                messageService.addMessage(message);
            }
            else
            {
                activity.setState("withdraw");
                activityDao.updateById(activity);
                message.setContent("活动审核未通过!");
                messageService.addMessage(message);
            }
        }
        else{
            //异常处理，返回审核失败
            throw new ActivityAdminException("审核活动失败");
        }
    }
}
